package org.moonlight.jvm.utils;

import org.moonlight.jvm.rtda.share.heap.Class;
import org.moonlight.jvm.rtda.share.heap.classmember.Method;

/**
 * 方法查找工具类
 *
 * @author Moonlight
 * @createTime 2023/9/12 9:50
 **/
public class MethodLookupUtil {

    public static Method lookupMethodInClass(Class clazz, String methodName, String methodDesc) {
        for (Class c = clazz; c != null; c = c.getSuperClass()) {
            if (c.getMethods() != null) {
                for (Method m : c.getMethods()) {
                    if (m.getName().equals(methodName) && m.getDescriptor().equals(methodDesc)) {
                        return m;
                    }
                }
            }
        }
        return null;
    }

    public static Method lookupMethodInInterfaces(Class[] interfaces, String methodName, String methodDesc) {
        for (Class face : interfaces) {
            for (Method m : face.getMethods()) {
                if (m.getName().equals(methodName) && m.getDescriptor().equals(methodDesc)) {
                    return m;
                }
            }
            Method m = lookupMethodInInterfaces(face.getInterfaces(), methodName, methodDesc);
            if (m != null) {
                return m;
            }
        }
        return null;
    }

}